-- 优先编码器 --
-- cs为片选端, 当cs为0时，编码器不工作，输出全部为1, 当cs为1时，输出全部为1
-- ex为扩展输出端,
-- out[1..0]输出为优先级最高的有效输入通道号的原码。
--------------

library ieee;
use ieee.std_logic_1164.all;

entity priority_encoder42 is
	port(
		d_i :	in std_logic_vector(3 downto 0);
		cs	: 	in std_logic;
		ex	:	out std_logic;
		d_o :	out std_logic_vector(1 downto 0)
	);
end;

architecture behave of priority_encoder42 is
begin
	process(cs, d_i)
	begin
		if cs = '0' then d_o <= "11"; ex <= '1';
		else
			if d_i(3) = '1' then d_o <= "11"; ex <= '0';
			elsif d_i(2) = '1' then d_o <= "10"; ex <= '0';
			elsif d_i(1) = '1' then d_o <= "01"; ex <= '0';
			elsif d_i(0) = '1' then d_o <= "00"; ex <= '0';
			end if;
		end if;
	end process;
end behave;



---------------
-- testbanch --
---------------

entity priority_encoder42_test is
end entity;

architecture test of priority_encoder42_test is
	
	signal cs, ex : std_logic;
	signal d_i : std_logic_vector(3 downto 0);
	signal d_o : std_logic_vector(1 downto 0);

	component priority_encoder42
	port(
		d_i :	in std_logic_vector(3 downto 0);
		cs	: 	in std_logic;
		ex	:	out std_logic;
		d_o :	out std_logic_vector(1 downto 0)
	);
	end component;

begin
	-- 实例化组件
	i1 : priority_encoder42
		port map(
			d_i => d_i;
			cs => cs;
			ex => ex;
			d_o => d_o;
		);

	-- 此进程中的内容只执行一次（wait）
	process begin
		cs <= '0', '1' after 20ns; wait;
	end process;
	
	-- 此进程中的代码循环执行
	process begin
		d_i <= "1000"; wait for 30ns;
		d_i <= "0100"; wait for 30ns;
		d_i <= "0010"; wait for 30ns;
		d_i <= "0001"; wait for 30ns;
	end process;


end test;